package com.mcc.app.group.task;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.mcc.app.group.domain.GroupClasses;
import com.mcc.app.group.domain.GroupSche;
import com.mcc.app.group.domain.GroupTeam;
import com.mcc.app.group.dto.GroupScheAutoDTO;
import com.mcc.app.group.service.IGroupClassesService;
import com.mcc.app.group.service.IGroupScheService;
import com.mcc.app.group.service.IGroupTeamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class GroupTask {

    @Autowired
    private IGroupClassesService groupClassesService;

    @Autowired
    private IGroupTeamService groupTeamService;

    @Autowired
    private IGroupScheService groupScheService;

    //每小时检查自动排班
    @PostConstruct
    @Scheduled(cron = "0 0 */1 * * ?")
    private void checkAutoSche() {
        Date nowDt = new Date();
        log.info("checkAutoSche nowDt is "+nowDt);
        checkAutoSche(nowDt);
        checkAutoSche(DateUtil.offsetHour(nowDt, 8));
        /*nowDt = DateUtil.parseDateTime("2024-09-15 00:00:00");
        for (int i = 0; i < 100; i++) {
//            System.out.println(DateUtil.formatDateTime(nowDt));
            checkAutoSche(nowDt);
            nowDt = DateUtil.offsetHour(nowDt, 8);
        }*/
    }

    private void checkAutoSche(Date nowDt) {
        GroupScheAutoDTO config = groupScheService.getAutoSche();
        if (config.getAutoScheEnable() == 1) {
            List<GroupClasses> classesList = groupClassesService.selectGroupClassesList(null);
            List<GroupTeam> teamList = new ArrayList<>();
            List<GroupTeam> tempList = groupTeamService.selectGroupTeamList(null);

            //初始排班
            GroupSche initGroupSche = new GroupSche();
            initGroupSche.setScheDate(config.getInitDate());
            initGroupSche.setClassesId(config.getClassesId());
            groupScheService.calTimeGroupSche(initGroupSche);

            //初始班次序号
//            int startOrder = getOrderByClasses(classesList, config.getClassesId());
            //初始日期周几
            int weekOrder = DateUtil.dayOfWeek(config.getInitDate());
            weekOrder--;

//            log.info("startOrder:{}", startOrder);
//            log.info("weekOrder:{}", weekOrder);

            int endOrder = getOrderByClasses(classesList, nowDt);//当前班次
//            log.info("endOrder:{}", endOrder);
//            int loopNum = Convert.toInt(Math.floor(DateUtil.between(initGroupSche.getStartDt(), nowDt, DateUnit.HOUR, false) / 24D)) + 1;
            int loopNum = Convert.toInt(Math.floor(DateUtil.between(initGroupSche.getStartDt(), nowDt, DateUnit.HOUR, false) / 24D));
//            log.info("loopNum:{}", loopNum);
            int overWeekNum = Convert.toInt(Math.ceil((loopNum + weekOrder) / 7D));//经过了几周

            switch (overWeekNum % 3) {
                case 1: {
                    //第一周
                    teamList.add(tempList.get(1));//乙
                    teamList.add(tempList.get(2));//丙
                    teamList.add(tempList.get(0));//甲
                    break;
                }
                case 2: {
                    //第二周
                    teamList.add(tempList.get(2));//丙
                    teamList.add(tempList.get(0));//甲
                    teamList.add(tempList.get(1));//乙
                    break;
                }
                case 0: {
                    //第三周
                    teamList.add(tempList.get(0));//甲
                    teamList.add(tempList.get(1));//乙
                    teamList.add(tempList.get(2));//丙
                    break;
                }
            }

            GroupClasses currentClasses = classesList.get(endOrder - 1);
            GroupTeam currentTeam = teamList.get(endOrder - 1);
            //根据当前时间获取排班
            GroupSche groupSche = groupScheService.getGroupScheByDt(nowDt);
            if (groupSche == null) {
                //未排班则自动排班
                groupSche = new GroupSche();
                groupSche.setScheDate(nowDt);
                groupSche.setClassesId(currentClasses.getClassesId());
                groupSche.setTeamId(currentTeam.getTeamId());
                groupScheService.calTimeGroupSche(groupSche, nowDt);


//                if (!(groupSche.getStartDt().getTime() <= nowDt.getTime() && nowDt.getTime() <= groupSche.getEndDt().getTime())) {
//                    groupSche.setScheDate(DateUtil.offsetDay(nowDt, -1));
//                    groupScheService.calTimeGroupSche(groupSche);
//                }
                groupScheService.insertGroupSche(groupSche);
            }
        }
    }

    private int getOrderByTeam(List<GroupTeam> teamList, Long teamId) {
        for (int i = 0; i < teamList.size(); i++) {
            GroupTeam row = teamList.get(i);
            if (NumberUtil.equals(teamId, row.getTeamId())) {
                return i + 1;
            }
        }
        return teamList.size();
    }

    private int getOrderByClasses(List<GroupClasses> classesList, Long classesId) {
        for (int i = 0; i < classesList.size(); i++) {
            GroupClasses row = classesList.get(i);
            if (NumberUtil.equals(classesId, row.getClassesId())) {
                return i + 1;
            }
        }
        return classesList.size();
    }

    private int getOrderByClasses(List<GroupClasses> classesList, Date dt) {
        String dateFormat = DateUtil.formatDate(dt);
        for (int i = 0; i < classesList.size(); i++) {
            GroupClasses row = classesList.get(i);

            Date startDt = DateUtil.parseDateTime(dateFormat + " " + row.getStartTime());
            Date endDt = DateUtil.parseDateTime(dateFormat + " " + row.getEndTime());
            if (startDt.getTime() > endDt.getTime()) {
                //看当前时间到底在哪个时间段里，前夜还是后夜
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(dt);
                int hour = calendar.get(Calendar.HOUR_OF_DAY);
                if(hour == 23 ) {
                    endDt = DateUtil.offset(endDt, DateField.DAY_OF_MONTH, 1);
                }else if(hour <= 7){//到后一天了
                    startDt = DateUtil.offset(startDt, DateField.DAY_OF_MONTH, -1);
                }

            }
            if (dt.getTime() >= startDt.getTime() && dt.getTime() < endDt.getTime()) {
                return i + 1;
            }
        }
        return classesList.size();
    }
}
